<?php
/**
 * Created by 张富琼 <zfuqiong@ifreegroup.com>.
 * User: kingzcheung
 * Date: 17-10-9
 * Time: 下午3:10
 */


namespace kingzcheung\migration\command\sql;


use kingzcheung\migration\command\Sql;
use kingzcheung\migration\Lock;
use kingzcheung\migration\SqlParse;
use think\console\Input;
use think\console\Output;
use think\console\input\Option as InputOption;
use think\Db;

class Run extends Sql {


    protected function configure() {
        $this->setName('sql:run')
            ->setDescription('运行SQL迁移')
            ->addOption('--file', '-f', InputOption::VALUE_REQUIRED, '指定迁移文件名')
            ->addOption('--date', '-d', InputOption::VALUE_REQUIRED, '指定日期')
            ->setHelp(<<<EOT
<info>sql:run</info> 命令运行所有可用的迁移, 可指定参数运行指定版本

<info>php think sql:run</info>
<info>php think sql:run -d 20110103081132</info>
<info>php think sql:run -f create_users_table</info>
<info>php think sql:run -v</info>

EOT
            );
    }


    protected function execute(Input $input, Output $output) {
        $file = $input->getOption('file');
        $date = $input->getOption('date');

        if (null != $date) {
            $this->runSqlToDate(new \DateTime($date));
        } else {
            $this->runSqlToName($file);
        }
    }

    public function runSqlToDate(\DateTime $dateTime) {
        $sqlfiles = $this->getSqls();
        $date     = $dateTime->format('Ymd');

        //过滤
        $sqlfilesByFiters = array_filter($sqlfiles, function ($k) use ($date) {
            return strpos($k, $date) !== false;
        }, ARRAY_FILTER_USE_KEY);

        foreach ($sqlfilesByFiters as $sqlfilesByFiter) {
            $this->runSql($sqlfilesByFiter);
        }
    }

    /**
     * @param string $filename
     *
     * @author 张富琼 <zfuqiong@ifreegroup.com>
     */
    public function runSqlToName($filename = '') {
        $sqlfiles = $this->getSqls();

        if (empty($sqlfiles)){
            $out = new Output();
            $out->writeln('<info>没有可执行的SQL.</info>');
            return ;
        }

        foreach ($sqlfiles as $key => $sqlfile) {
            if (!empty($filename)) {
                preg_match("/[a-zA-Z_]+/", basename($sqlfile), $matches);
                if ($filename === trim($matches[0], '_')) {
                    $this->runSql($sqlfile);
                    break;
                }
            }

            $this->runSql($sqlfile);

        }

    }

    /**
     *
     * @param $file
     *
     * @author 张富琼 <zfuqiong@ifreegroup.com>
     */
    private function runSql($file) {
        $parse = new SqlParse($file);
        $sqls  = $parse->sqls();
        if (sizeof($sqls) == 0) return;

        foreach ($sqls as $sql) {
            if (strpos(strtolower($sql), 'select') !== false) {
                continue;
            }
            else {
                Db::execute($sql);
            }
        }

        $sqlName = basename($file);
        $time = date('YmdHis');
        Lock::push([$sqlName,$time]);
    }

    private function getSqlforFile($file) {
        $parse = new SqlParse($file);
        $parse->sqls();
    }
}